#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <wiringPi.h>

#include "control.h"
#include "msg_queue.h"
#include "voice_interface.h"
#include "global.h"
#include "socket_interface.h"
#include "smoke_interface.h"
#include "receive_interface.h"

int main(int argc,char *argv[])
{
    pthread_t thread_id;
    struct control *control_phead = NULL;
    struct control *pointer = NULL;
    ctrl_info_t *ctrl_info = NULL;

    ctrl_info = (ctrl_info_t *)malloc(sizeof(ctrl_info_t));
    ctrl_info->ctrl_phead = NULL;
    ctrl_info->mqd = -1;

    int node_num = 0;

    wiringPiSetup();
    ctrl_info->mqd = msg_queue_create();

    if(ctrl_info->mqd == -1)
    {
        printf("msg_queue_create failed \n");
        return -1;
    }

    ctrl_info->ctrl_phead = add_voice_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_tcpsocket_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_smoke_to_ctrl_list(ctrl_info->ctrl_phead);
    ctrl_info->ctrl_phead = add_receive_to_ctrl_list(ctrl_info->ctrl_phead);

    pointer = ctrl_info->ctrl_phead;
    while(pointer != NULL)
    {
        if(pointer->init != NULL)
        {
            pointer->init();
        }
        pointer = pointer->next;
        node_num ++;
    }

    pthread_t *tid = malloc(sizeof(int)*node_num);

    pointer = ctrl_info->ctrl_phead;
    for(int i=0;i<node_num;i++)
    {
        if(pointer->get != NULL)
        pthread_create(&tid[i],NULL,(void*)pointer->get,(void*)ctrl_info);
        pointer = pointer->next;
    }

    for(int i=0;i<node_num;i++)
    {
        pthread_join(tid[i],NULL);
    }

    for(int i=0;i<node_num;i++)
    {
        if(pointer->final != NULL)
            pointer->final();
        pointer = pointer->next;
    }

    msg_queue_final(ctrl_info->mqd);

    return 0;
}